package com.bstek;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * @description: 转换null对象为空字符串
 */
public class JsonObjectMapper extends ObjectMapper {
	private static final long serialVersionUID = 1L;

	public JsonObjectMapper() {
		super();
		// 空值处理为空串
		this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator jg, SerializerProvider sp)
					throws IOException, JsonProcessingException {
				jg.writeString("");
			}
		});
		// 反序列化
		// 从JSON到java object,没有匹配的属性名称时不作失败处理
		this.configure(MapperFeature.AUTO_DETECT_FIELDS, true);// 反序列化
		// 禁止遇到空原始类型时抛出异常，用默认值代替。
		this.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
		this.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
		// 禁止遇到未知（新）属性时报错，支持兼容扩展
		this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

		// 序列化
		// 禁止序列化空值
		this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		this.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
		this.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
		this.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
		// 格式化输出
		this.configure(SerializationFeature.INDENT_OUTPUT, true);

		// 不包含空值属性
		this.setSerializationInclusion(Include.NON_EMPTY);

	}
}
